from django.contrib.auth.models import User
from django.contrib import auth
from .models import UserInformation
from .serializers import LoginSerializer, RegisterSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from backend.views import get_first_error


class Login(APIView):  # 登录相关视图类
    def post(self, request):  # 用户登录，提交post数据
        context = dict()
        data = LoginSerializer(data=request.POST)
        if not data.is_valid():  # 验证有效性
            errors = data.errors
            key, value = get_first_error(errors)
            context['error'] = key + ' ' + value[0]
            context['err_code']=2002
        else:
            context['data']=dict()
            data = data.data
            username = data['username']
            password = data['password']
            user = auth.authenticate(username=username, password=password)
            if user is None:
                context['data']['error'] = "用户名或密码错误"
                context['data']['result'] = False
            else:  # 验证通过
                auth.login(request, user)
                if not data['remember']:  # 如果没有勾选14天免登录
                    request.session.set_expiry(0)
                context['data']['nickname'] = request.user.get_short_name()
                context['data']['result']=True
            context['err_code'] = 0
        return Response(context)

    def get(self, request):  # 检测用户是否登录
        context = dict()
        if not request.user.is_anonymous:
            context['err_code']=0
            context['data']=dict()
            context['data']['nickname']=request.user.get_short_name()
            context['data']['result']=True
        else:
            context = dict()
            context['err_code'] = 0
            context['data'] = dict()
            context['data']['result'] = False
        return Response(context)


class Register(APIView):  # 注册相关视图类
    def post(self, request):
        context = dict()
        data = RegisterSerializer(data=request.POST)
        if not data.is_valid():  # 验证数据的有效性，如果无效证明绕过了前端
            context['err_code']=4002
            errors = data.errors
            key, value = get_first_error(errors)
            context['error'] = key + ' ' + value[0]
        else:

            data = data.data
            username = data['username']
            password = data['password']
            nickname = data['nickname']
            email = data['email']
            context['data']=dict()
            context['data']['result']=True
            if User.objects.filter(username=username).exists():
                context['data']['error']="用户名已存在"
                context['data']['result'] = False
            if context['data']['result'] and User.objects.filter(email=email).exists():
                context['data']['error'] = "邮箱已存在"
                context['data']['result'] = False
            if context['data']['result'] and User.objects.filter(first_name=nickname).exists():
                context['data']['error'] = "昵称已存在"
                context['data']['result'] = False
            if context['data']['result']:
                User.objects.create_user(username=username, password=password, email=email, first_name=nickname)
                information = UserInformation()  # 注册一个用户就生成对应的用户信息
                information.auth = User.objects.get(username=username)
                information.save()
            context['err_code']=0
        return Response(context)


class LogOut(APIView):  # 登出
    def get(self, request):
        auth.logout(request)
        context = dict()
        context['err_code']=0
        context['data']=dict()
        context['data']['result']=True
        return Response(context)


# TODO:忘记密码没写
class Forget(APIView):  # 忘记密码 ，向用户发送邮件
    def get(self, request):  # 如果是get，那么发送验证码
        pass
